package strings;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 请从字符串中找出一个最长的不包含重复字符的子字符串，计算该最长子字符串的长度。
 * 输入: "abcabcbb"
 * 输出: 3
 * 解释: 因为无重复字符的最长子串是 "abc"，所以其长度为 3
 * @author le
 */
public class MaxLengthUnDupliexSubString
{
    public static void main(String[] args)
    {
        System.out.println(lengthOfLongestSubstring("pwwkew"));
    }

    /**
     * 自己的垃圾思路
     * @param s
     * @return
     */
    public static int lengthOfLongeststring(String s) {
        char[] arr = s.toCharArray();
        List<Character> res = new ArrayList<>();
        int maxLength = 1;
        int count = 0;
        for (int i = 0;i < arr.length;i++){
            if (res.contains(arr[i])){
                res.clear();
                res.add(arr[i]);
                maxLength = maxLength > count?maxLength:count;
                count= 1;
            }else{
                res.add(arr[i]);
                count++;
            }
        }
        return maxLength;
    }

    public static int lengthOfLongestSubstring(String s){
        if (s == null || s.length() <= 0){
            return 0;
        }

        int leftIndex = -1;
        int result = 0;
        Map<Character, Integer> leftIndexMap = new HashMap<>();
        char[] arr = s.toCharArray();
        for (int i = 0;i < arr.length;i++){
            if (leftIndexMap.containsKey(arr[i])){
                // 之前已经出现过更新滑动窗口的左边界
                leftIndex = Math.max(leftIndex, leftIndexMap.get(arr[i]));
            }
            leftIndexMap.put(arr[i],i);
            result = Math.max(result, i-leftIndex);
        }
        return result;
    }
}
